//
//  NetService.swift
//  Config
//
//  Created by xiute on 2018/10/30.
//

import UIKit
import AFNetworking

public let RQServiceErrorDomain = "RQServiceErrorDomain"

public typealias ServiceComplete = (_ success: Bool, _ error: NSError?, _ dataTask: URLSessionDataTask, _ response: Any?) -> Void

public class RQNetService: NSObject {
    public static let shareInstance = RQNetService()
    private override init() {
        
    }
    
    public func rq_get(urlString:String, parameter: Any?, complete: @escaping ServiceComplete) -> URLSessionDataTask? {
        print("为什么方法没有进来")
        let dataTask = self.afManager.get(urlString, parameters: parameter, progress: nil, success: { (dataTask, response) in
            if response is Data {
                self.handleSuccess(response: response, complete: complete, dataTask)
            }else {
                let error = NSError(domain: RQServiceErrorDomain, code: -1, userInfo: nil)
                complete(false, error, dataTask, nil)
            }

        }) { (dataTask, swiftError) in
            print(swiftError)
        }
        return dataTask
    }
    
    func handleSuccess(response: Any?, complete: ServiceComplete, _ dataTask: URLSessionDataTask) -> Void {
        //可以做一些成功的打点记录之类的
        do {
            let responseDic = try JSONSerialization.jsonObject(with: response as! Data, options: JSONSerialization.ReadingOptions.mutableContainers)
            complete(true, nil, dataTask, responseDic)
        } catch {
            let error = NSError(domain: RQServiceErrorDomain, code: -2, userInfo: nil)
            complete(false, error, dataTask, nil)
        }
        
    }
    
    
    
    //MARK: -properties lazy load
    lazy var afManager: AFHTTPSessionManager = {
        let afManager: AFHTTPSessionManager = AFHTTPSessionManager(baseURL: URL(string: "https://pastebin.com"))
        let requestSerializer = AFHTTPRequestSerializer()
        let responseSerializer = AFHTTPResponseSerializer()
        
        afManager.requestSerializer = requestSerializer
        afManager.responseSerializer = responseSerializer
        return afManager
    }()
}
